package com.yun.baymax.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.yun.baymax.R;
import com.yun.baymax.bean.ChatUser;
import com.yun.baymax.bean.User;
import com.yun.baymax.cache.ChatUserCache;
import com.yun.baymax.cache.UserCache;
import com.yun.baymax.utils.GlideUtils;
import com.yun.lib.fragment.BaseFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

public class MoreFragment extends BaseFragment implements TakePhoto.TakeResultListener, InvokeListener {
    private static Context context;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tab_bar)
    TabLayout tabBar;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.bar_background)
    ImageView barBg;
    private User bmUser;
    private User localUser;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private List<Fragment> fms = new ArrayList<>();
    private String[] titles = {"个人主页", "设置"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();
        takePhoto = getTakePhoto();
    }

    @Override
    protected int setLayoutResourceId() {
        return R.layout.fragment_more3;
    }

    @Override
    protected void initViews(Bundle savedInstanceState, View view, LayoutInflater inflater) {
        ButterKnife.bind(this, view);
        initViewData();
//        ((MainActivity) getActivity()).setSupportActionBar(toolbar);

        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChooseDialog(null);
            }
        });
        fms.clear();
        fms.add(new ProfileFragment());
        fms.add(new SettingsFragment());
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
        tabBar.setupWithViewPager(viewPager);
    }

    @Override
    protected void loadData() {
    }

    private void initViewData() {
        localUser = UserCache.getInstance().getCurrentUser();
        bmUser = BmobUser.getCurrentUser(User.class);
        if (bmUser == null)
            return;
        localUser = localUser == null ? bmUser : localUser;

        String headImageUrl = localUser.getHeadImage();
        if (!TextUtils.isEmpty(headImageUrl)) {
            Glide.with(context).load(headImageUrl).into(barBg);
            Glide.with(context).load(headImageUrl).asBitmap().into(GlideUtils.setCircle(context, ivHead));
        } else
            Glide.with(context).load(R.drawable.avatar).asBitmap().into(GlideUtils.setCircle(context, ivHead));
    }

    private void updateUserInfo(User user) {
        UserCache.getInstance().updateUser(localUser);
        localUser.setEmail(null);
        localUser.update(user.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    showToast("更新成功");
                    initViewData();
                } else {
                    showToast("更新失败" + e.getMessage());
                }
            }
        });
    }

    private void uploadImage(String path) {
        final BmobFile bmobFile = new BmobFile(new File(path));
        bmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    //bmobFile.getFileUrl()--返回的上传文件的完整地址
                    String imgUrl = bmobFile.getFileUrl();
                    bmUser.setHeadImage(imgUrl);
                    localUser.setHeadImage(imgUrl);
                    ChatUser chatUser = ChatUserCache.getInstance().getChatUser(localUser.getHxName());
                    chatUser.setHeadImage(imgUrl);
                    ChatUserCache.getInstance().updateChatUser(chatUser);

                    updateUserInfo(bmUser);
                } else {
                    showToast("上传文件失败：" + e.getMessage());
                }
            }
        });
    }

    @Override
    public void takeSuccess(TResult tResult) {
        String originalPath = tResult.getImage().getOriginalPath();
        if (!TextUtils.isEmpty(originalPath)) {
            uploadImage(originalPath);
            //本地文件
            File file = new File(originalPath);
            Glide.with(context).load(file).asBitmap().into(GlideUtils.setCircle(context, ivHead));
        } else Toast.makeText(context, "请重新选取照片", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void takeFail(TResult tResult, String s) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void showChooseDialog(View animateView) {

        final String stringItems[] = new String[]{"拍照", "手机相册"};
        final ActionSheetDialog dialog = new ActionSheetDialog(context, stringItems, animateView);
        dialog.isTitleShow(false).show();

        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        final Uri imageUri = Uri.fromFile(file);

        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
                        break;
                    case 1:
                        takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());
                        break;
                    default:
                        break;
                }
                dialog.dismiss();
            }
        });

    }

    private CropOptions getCropOptions() {
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(1).setAspectY(1);
        builder.setOutputX(300).setOutputY(300);
        return builder.create();
    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fms.get(position);
        }

        @Override
        public int getCount() {
            return fms.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}
